package top.xxyu.app.admin.controller;

import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import top.xxyu.common.util.SFTPUtils;

@Controller
public class ImgController {

	@RequestMapping(value = "/img", method = RequestMethod.GET)
	public void gallery(String name, HttpServletRequest req, HttpServletResponse res) {
		try {
			File file = null;
			ClassLoader classLoader = this.getClass().getClassLoader();
			URL folder = classLoader.getResource("static/upload");
			if (null == folder) {
				SFTPUtils.download(name, classLoader.getResource("static").getPath()+"/upload/"+name);
			} else {
				String filePath = folder.getPath();
				file = new File(filePath+"/"+ name);
				if (!file.exists()) {
					SFTPUtils.download(name, file.getPath());
				}
			}
			res.setContentType("application/x-jpg");
//			res.addHeader("Content-Disposition", "attachment;filename=image.png");
			FileInputStream stream = new FileInputStream(file);
			byte[] b = new byte[stream.available()];
			stream.read(b);
			ServletOutputStream out = res.getOutputStream();
			out.write(b);
			out.flush();
			out.close();
			stream.close();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
